//
//  AppDelegate.m
//  ImGuider
//
//  Created by 李陆涛 on 2017/8/2.
//  Copyright © 2017年 AudioCtrip. All rights reserved.
//

#import "AppDelegate.h"

#import <UMSocialCore/UMSocialCore.h>
#import <Bugly/Bugly.h>
#import "IAPManager.h"
#import <StoreKit/StoreKit.h>
#import "DownloadListDAO.h"
#import "PhoneInfo.h"

#import <SDWebImageManager.h>
#import <MWApi.h>

#import "UMessage.h"
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate ()<SKProductsRequestDelegate, UNUserNotificationCenterDelegate>

@property (nonatomic, strong) NSDictionary *userInfo;

@end

@implementation AppDelegate

- (void)initAppWithOP:(NSDictionary *)launchOptions {
    
    BOOL hasInApp = [[NSUserDefaults standardUserDefaults] boolForKey:@"hasInApp"];
    
    if (hasInApp) {
        
        [NetAPIManager getAppVersionBlock:nil];
        [[IAPManager sharedManager] startManager];
        [self configCacheData];
        [self setupUMeng:launchOptions];
        [self setupMW];
//        [self setupCurrency];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSInteger openTimes = [[NSUserDefaults standardUserDefaults] integerForKey:@"openTimes"];
            [[NSUserDefaults standardUserDefaults] setInteger:(openTimes + 1) forKey:@"openTimes"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        });
    }
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        [AppManager sharedManager].networkState = status;
        
        if (status != AFNetworkReachabilityStatusNotReachable && !hasInApp) {
            
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasInApp"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    NSDate *date = [NSDate date];
                    [[NSUserDefaults standardUserDefaults] setObject:date forKey:@"insertAppTime"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                });
                
                [NetAPIManager getAppVersionBlock:nil];
                [self setupUMeng:launchOptions];
                [self setupMW];
            });
        }
    }];
}

// ------------------获取币种-------------------------------------

- (void)setupCurrency {
    // 获取apple id当前地区
    SKProductsRequest *request = [[SKProductsRequest alloc]initWithProductIdentifiers:[NSSet setWithObject:@"imguider.yk.600"]];
    
    request.delegate = self;
    
    [request start];
}

// 获取apple id当前地区
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    
    NSArray *myProduct = response.products;
    
    if ([myProduct count] == 0) {
        return;
    }
    
    for (SKProduct *product in myProduct) {
        
        NSString *countryCode = [product.priceLocale objectForKey:NSLocaleCountryCode];
        [AppManager sharedManager].currentCountryCode = countryCode;
    }
}
// ------------------设置魔窗 统计渠道用-------------------------------------
- (void)setupMW {
    
    [MWApi registerApp:MW_KEY];
    
    [MWApi registerMLinkHandlerWithKey:@"channel" handler:^(NSURL *url, NSDictionary *params) {
        //自行处理跳转逻辑，示例如下：
        
        NSString *chid = params[@"chid"];
        
        NSMutableDictionary *daDict = [NSMutableDictionary dictionaryWithDictionary:@{@"lat":@([LocationManager sharedManager].currentLocation.coordinate.latitude),@"lng":@([LocationManager sharedManager].currentLocation.coordinate.longitude)}];
        
        if (chid) {
            
            [UserManager sharedManager].chid = chid;
            [daDict setObject:chid forKey:@"chid"];
            [MWApi setChannelId:chid];
        }
        [NetAPIManager postPhoneData:daDict];
    }];
    
    
    [MWApi registerMLinkHandlerWithKey:@"detail" handler:^(NSURL *url, NSDictionary *params) {
        //自行处理跳转逻辑，示例如下：
        
        NSString *lineid = params[@"lineid"];
        
        NSMutableDictionary *daDict = [NSMutableDictionary dictionaryWithDictionary:@{@"lat":@([LocationManager sharedManager].currentLocation.coordinate.latitude),@"lng":@([LocationManager sharedManager].currentLocation.coordinate.longitude)}];
        
        if (lineid) {
            
            [daDict setObject:lineid forKey:@"opendetailid"];
            
            OperationObject *obj = [OperationObject new];
            obj.opid = lineid;
            obj.type = 1;
            [AppManager sharedManager].opObj = obj;
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshMainVCNotif object:nil];
        }
        [NetAPIManager postPhoneData:daDict];
        
    }];
}
// ------------------初始化友盟-------------------------------------
- (void)setupUMeng:(NSDictionary *)launchOptions {
    
    UMConfigInstance.appKey = UMENG_APPKEY;
    UMConfigInstance.channelId = [UserManager sharedManager].chid ? [UserManager sharedManager].chid : @"AppStore";
    
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    [MobClick setAppVersion:kVersion];
    
    /* 打开调试日志 */
    [[UMSocialManager defaultManager] openLog:YES];
    
    /* 设置友盟appkey */
    [[UMSocialManager defaultManager] setUmSocialAppkey:UMENG_APPKEY];
    
    
    [UMessage startWithAppkey:UMENG_APPKEY launchOptions:launchOptions httpsenable:YES];
    [UMessage setBadgeClear:YES];
    [UMessage setAutoAlert:NO];
    
    //注册通知，如果要使用category的自定义策略，可以参考demo中的代码。
    [UMessage registerForRemoteNotifications];
    
    //iOS10必须加下面这段代码。
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    
    UNAuthorizationOptions types10 = UNAuthorizationOptionBadge|  UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
    
    [center requestAuthorizationWithOptions:types10 completionHandler:^(BOOL granted, NSError * _Nullable error) {
        
        if (granted) {
            //点击允许
            //这里可以添加一些自己的逻辑
        } else {
            //点击不允许
            //这里可以添加一些自己的逻辑
        }
    }];
    
//    初始化分享，登录平台
    [self configUSharePlatforms];
}

- (void)configUSharePlatforms {
    
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:UMENG_WX_APPID appSecret:UMENG_WX_APPSECRET redirectURL:kRedirectURL];
    
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:UMENG_QQ_APPID  appSecret:nil redirectURL:kRedirectURL];
    
    /* 设置新浪的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:UMENG_WB_APPKEY  appSecret:UMENG_WB_APPSECRET redirectURL:@"https://api.weibo.com/oauth2/default.html"];
    
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Twitter appKey:@"fB5tvRpna1CKK97xZUslbxiet"  appSecret:@"YcbSvseLIwZ4hZg9YmgJPP5uWzd4zr6BpBKGZhf07zzh3oj62K" redirectURL:nil];
    
    /* 设置Facebook的appKey和UrlString */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Facebook appKey:UMENG_FB_APPID  appSecret:nil redirectURL:kRedirectURL];
    
    /* 设置bugly */
    [Bugly startWithAppId:BUGLY_APPID];
}


/**
 应用升级，清楚缓存 （防止数据结构发生变化，造成崩溃）
 */
- (void)configCacheData {
    
    [[DownloadManager sharedManager] deleteAllDownloading];
    //设置30天，默认是7天
    [[SDWebImageManager sharedManager].imageCache.config setMaxCacheAge:60 * 60 * 24 * 30];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [[LocationManager sharedManager] startUpdatingLocation];
    [self initAppWithOP:launchOptions];
    
    return YES;
}


//---------------------------- 第三方登录回调
// 仅支持iOS9以上系统，iOS8及以下系统不会回调
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
    
    return [self callbackWithURL:url];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation {
    
    return [self callbackWithURL:url];
}

// 支持目前所有iOS系统
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    
    return [self callbackWithURL:url];
}

- (BOOL)callbackWithURL:(NSURL *)url {
    
    [MWApi routeMLink:url];
    
    return [[UMSocialManager defaultManager] handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray * __nullable restorableObjects))restorationHandler {
    
    return [MWApi continueUserActivity:userActivity];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    
    [self resignFirstResponder];
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    if (event.type == UIEventTypeRemoteControl) {

        switch (event.subtype) { // 得到事件类型

            case UIEventSubtypeRemoteControlTogglePlayPause: // 暂停 ios6
                
                [[IGAvPlayerManager shareManeger] pause];
                // 调用你所在项目的暂停按钮的响应方法 下面的也是如此
                break;

            case UIEventSubtypeRemoteControlPreviousTrack:  // 上一首
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"remotePre" object:nil userInfo:nil];
                break;

            case UIEventSubtypeRemoteControlNextTrack: // 下一首
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"remoteNext" object:nil userInfo:nil];
                break;

            case UIEventSubtypeRemoteControlPlay: //播放
                [[IGAvPlayerManager shareManeger] play];
                break;

            case UIEventSubtypeRemoteControlPause: // 暂停 ios7
                // [self actionStopButton:self.musicViewNew.stopButton];
                [[IGAvPlayerManager shareManeger] pause];
                break;

            default:

                break;
        }
    }
}

- (void)pushWithUserInfo:(NSDictionary *)userInfo {
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    [UMessage sendClickReportForRemoteNotification:userInfo];
    self.userInfo = userInfo;
    
    if ([userInfo[@"type"] isEqualToString:@"answer"] && [UserManager sharedManager].token) {
        
        [NetAPIManager getUserInfoWithBlock:^(NSString *result, NSError *error) {
            
            if (!error) {
                [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshUserNotif object:nil];
            }
        }];
    }
    
    //定制自定的的弹出框
    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:userInfo[@"aps"][@"alert"][@"title"]
                                                            message:userInfo[@"aps"][@"alert"][@"body"]
                                                           delegate:self
                                                  cancelButtonTitle:MYLocalizedString(@"PUBLIC_CONFIRM", nil)
                                                  otherButtonTitles:nil];

        [alertView show];

    }
}

//iOS10以前接收的方法
- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler {
    
    [self pushWithUserInfo:userInfo];
}
//iOS10以下使用这个方法接收通知
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    [UMessage didReceiveRemoteNotification:userInfo];
    
    [self pushWithUserInfo:userInfo];
}

//iOS10新增：处理前台收到通知的代理方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于前台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        //应用处于前台时的本地推送接受
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge);
    
    [self pushWithUserInfo:userInfo];
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        //应用处于后台时的本地推送接受
    }
    [self pushWithUserInfo:userInfo];
}


@end
